import sys
import pygame
from config import Config
from ball import Ball
from paddle import Paddle
from brick_wall import BrickWall
from score import Score
from sound import SoundManager
from hello import Hello
from settings import SettingsMenu
from speed_menu import SpeedMenu


class Breakout:
    def __init__(self):
        pygame.init()
        self.config = Config()
        self.screen = pygame.display.set_mode(
            (self.config.screen_width, self.config.screen_height))
        pygame.display.set_caption('弹跳球')
        self.clock = pygame.time.Clock()

        # 显示开始页面
        self.hello = Hello(self.screen, self.config)
        self.current_level = self.hello.run()

        self.paddle = Paddle(self)
        self.ball = Ball(self)
        self.score = Score(self.config)
        self.sound = SoundManager()
        self.current_level = 1
        self.brick_wall = BrickWall(self, self._get_level_type())

        self.game_over = False
        self.game_started = False
        self.countdown_start = pygame.time.get_ticks()
        self.setting_menu = SettingsMenu(self.screen, self.config)
        self.setting_menu_active = False
        self.current_level = self.hello.run()  # 获取用户选择的关卡
        self.brick_wall = BrickWall(self, self._get_level_type())  # 根据关卡生成砖块


    def _get_level_type(self):
        level_types = ["genetic", "flocking"]
        return level_types[self.current_level - 1]  # 根据关卡选择类型

    def run_game(self):
        while True:
            self._handle_events()
            if not self.game_over and self.game_started:
                self._update_game()
            self._draw()
            self.clock.tick(self.config.fps)

    def _handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self._quit_game()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self._toggle_setting_menu()
                if event.key == pygame.K_r and self.game_over:
                    self._reset_game()

    def _toggle_setting_menu(self):
        self.setting_menu_active = not self.setting_menu_active
        if self.setting_menu_active:
            self._pause_game()
        else:
            self._resume_game()

    def _show_setting_menu(self):
        while self.setting_menu_active:
            selected_option = self.setting_menu.handle_events()
            if selected_option != -1:
                self._process_setting_option(selected_option)
            self.setting_menu.draw()

    def _process_setting_option(self, option):
        if option == 0:  # 继续游戏
            self._resume_game()
        elif option == 1:  # 小球速度
            self._show_speed_menu()
        elif option == 2:  # 退出游戏
            self._quit_game()
        elif option == 3:  # 暂停游戏
            self._pause_game()
        elif option == 4:  # 返回开始界面
            self._return_to_main_menu()

    def _pause_game(self):
        self.game_paused = True
        self._show_setting_menu()

    def _resume_game(self):
        self.game_paused = False
        self._hide_setting_menu()

    def _show_speed_menu(self):
        """
        显示速度调节菜单，支持调节小球和砖块速度。
        """
        speed_menu_active = True
        speed_menu = SpeedMenu(self.screen, self.config, self)

        while speed_menu_active:
            self.screen.fill(self.config.colors['black'])
            speed_menu.draw()
            speed_menu.handle_events()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self._quit_game()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        speed_menu_active = False
                    elif event.key == pygame.K_RETURN:
                        speed_menu_active = False

            # 处理速度调节菜单事件
            result = speed_menu.handle_events()
            if result == 0:  # 返回设置界面
                speed_menu_active = False

            pygame.display.flip()

    def _return_to_main_menu(self):
        """
        返回到游戏的开始界面，重置游戏状态并显示选择关卡的菜单。
        """
        self.game_over = True  # 标记游戏结束
        self.game_started = False  # 标记游戏未开始
        self.current_level = 1  # 重置当前关卡
        self.score.reset()  # 重置分数
        self.ball.reset()  # 重置小球位置和速度
        self.brick_wall = BrickWall(self, self._get_level_type())  # 重新生成砖块墙
        self.hello = Hello(self.screen, self.config)  # 重新初始化开始界面
        self.hello.run()  # 显示开始界面

    def _adjust_ball_speed(self):
        """
        调整小球的速度，确保速度在合理范围内。
        """
        # 增加小球速度，确保不超过最大速度
        self.ball.velocity.scale_to_length(self.ball.velocity.length() + 1)
        if self.ball.velocity.length() > self.config.ball_MAX_SPEED:
            self.ball.velocity.scale_to_length(self.config.ball_MAX_SPEED)
        # 减少小球速度，确保不低于最小速度
        elif self.ball.velocity.length() < 2.0:
            self.ball.velocity.scale_to_length(2.0)

        # 打印当前速度供调试
        print(f"当前小球速度: {self.ball.velocity.length()}")

    def _hide_setting_menu(self):
        """
        隐藏设置菜单，恢复游戏主界面的显示。
        """
        self.setting_menu_active = False  # 标记设置菜单为隐藏状态
        self.screen.fill(self.config.colors['black'])  # 清空屏幕，恢复背景色
        self._draw()  # 重新绘制游戏界面
        pygame.display.flip()  # 更新屏幕显示

    @staticmethod
    def _quit_game():
        pygame.quit()
        sys.exit()

    def _update_game(self):
        keys = pygame.key.get_pressed()
        self.paddle.update(keys)

        if self.ball.update(self.paddle.rect):
            self.sound.play('paddle_hit')

        # 砖块碰撞检测
        bricks_broken = self.brick_wall.check_collision(self.ball)
        if bricks_broken:
            self.score.update_score(bricks_broken * 10)
            self.sound.play('brick_break')

        # 关卡切换
        if not self.brick_wall.bricks:
            self.current_level += 1
            self.brick_wall = BrickWall(self, self._get_level_type())
            self.ball.reset()

        # 游戏结束检测
        if self.ball.rect.top > self.config.screen_height:
            self.game_over = True

    def _draw(self):
        self.screen.fill(self.config.colors['black'])
        self._draw_countdown()

        if self.game_started:
            self.paddle.draw(self.screen)
            self.screen.blit(self.ball.image, self.ball.rect)
            self.brick_wall.bricks.draw(self.screen)
            self.score.draw(self.screen)

            if self.game_over:
                self._draw_game_over()

        pygame.display.flip()

    def _draw_countdown(self):
        if not self.game_started:
            current_time = pygame.time.get_ticks()
            elapsed_time = current_time - self.countdown_start
            if elapsed_time < 3000:
                countdown_number = 3 - (elapsed_time // 1000)
                text = self.config.countdown_font.render(
                    str(countdown_number), True, self.config.colors['white'])
                self.screen.blit(text, (self.config.screen_width // 2 - 30, self.config.screen_height // 2 - 50))
            else:
                self.game_started = True

    def _draw_game_over(self):
        text = self.config.countdown_font.render(
            "请按 [R] 重开", True, self.config.colors['white'])
        self.screen.blit(text, (self.config.screen_width // 2 - 220, self.config.screen_height // 2))

    def _reset_game(self):
        self.game_over = False
        self.current_level = 1
        self.score.reset()
        self.ball.reset()
        self.brick_wall = BrickWall(self, self._get_level_type())
        self.countdown_start = pygame.time.get_ticks()
        self.game_started = False


